from flask import Flask , render_template,request, url_for, flash, redirect
from flask_login import LoginManager, current_user, login_required, UserMixin
from gevent import pywsgi
from database_operations import execute_query, fetch_data
from file_operations import UPLOAD_FOLDER, upload_image,delete_file
from auth_app import auth_app

app = Flask(__name__)  #创建一个 flask 对象 名字就是 文件名
app.config['SECRET_KEY']='xu jiang 666'
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER #将文件上传目录的配置信息传递给 Flask 应用

# 初始化 Flask-Login
login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = 'auth.login'  # 设置登录视图

# 定义 User 类
class User(UserMixin):
    def __init__(self, id, username):
        self.id = id
        self.username = username

# 定义 user_loader 回调函数
@login_manager.user_loader
def load_user(user_id):
    # 根据用户 ID 从数据库获取用户信息
    user_data = fetch_data('SELECT id, username FROM users WHERE id = %s', (user_id,))
    if user_data:
        user = User(id=user_data[0]['id'], username=user_data[0]['username'])
        return user
    return None

# 注册蓝图
app.register_blueprint(auth_app, url_prefix='/auth')


# 分页每页显示的数量
PER_PAGE = 10

@app.route('/')   # 使用路由，给 index 函数定义一个路由，然后游览器通过http 请求得到相对应的数据
def index():
    posts = fetch_data('SELECT * FROM posts')
    return render_template('index.html', posts=posts)

def get_post(post_id):
    post = fetch_data('SELECT * FROM posts WHERE id=%s', (post_id,))
    return post[0] if post else None

@app.route('/posts/<int:post_id>')
def post(post_id):
    post = get_post(post_id)
    return render_template('post.html', post=post)

@app.route('/posts/new', methods=('GET', 'POST'))
def new():
    if request.method == 'POST':
        title = request.form['title']
        content = request.form['content']
        filename = None
        if 'image' in request.files:
            file = request.files['image']
            if file.filename != '':
                filename = upload_image(file, app.config['UPLOAD_FOLDER'])
                if filename is None:
                    flash('不支持的文件类型')
                    return redirect(request.url)
        if not title:
            flash('标题不能为空!')
        elif not content:
            flash('内容不能为空')
        else:
            execute_query('INSERT INTO posts (title, content, image_filename) VALUES (%s, %s, %s)', (title, content, filename))
            flash('文章发布成功!')
            return redirect(url_for('index'))

    return render_template('new.html')

@app.route('/posts/<int:id>/edit', methods=('GET', 'POST'))
def edit(id):
    post = get_post(id)
    # 打印调试信息
    print(post)
    if request.method == 'POST':
        title = request.form['title']
        content = request.form['content']
        original_filename = post['image_filename']  # 获取原始的图片文件名
        print(f"Original post data: {post}")
        #处理图片上传
        if 'image' in request.files:
            file = request.files['image']
            if file.filename != '':
                # 上传新的图片并获取新的文件名
                new_filename = upload_image(file, app.config['UPLOAD_FOLDER'])
                if new_filename is None:
                    flash('不支持的文件类型')
                    return redirect(request.url)
                original_filename = new_filename  # 更新为新的文件名
        #更新文章的标题和内容
        if not title:
            flash("标题不能为空!")
        else:
            execute_query('UPDATE posts SET title = %s, content = %s, image_filename = %s WHERE id = %s', (title, content, original_filename, id))
            flash('文章更新成功!')
            updated_post = get_post(id)
            print(f"Updated post data: {updated_post}")
            return redirect(url_for('index'))

    return render_template('edit.html', post=post)

@app.route('/posts/<int:id>/delete', methods=['POST', 'DELETE'])
def delete(id):
    post = get_post(id)
    # 打印调试信息
    print(f"删除 post 返回: {post}")
    if post is None:
        flash('文章不存在或已删除!')
        return redirect(url_for('index'))
    image_filename = post['image_filename']
    # 删除数据库中的文章记录
    execute_query('DELETE FROM posts WHERE id = %s', (id,))
    # 删除文件系统中的对应文件
    if image_filename:
        upload_folder = app.config['UPLOAD_FOLDER']
        delete_file(upload_folder, image_filename)
    flash('"{}" 删除成功!'.format(post['title']))
    return redirect(url_for('index'))

@app.route('/about')
def about():
    return render_template('about.html') #查找templates目录下的about.html文件（即模板），将其转换为 HTML，返回给浏览器作为响应

@app.route('/vegetable_baskets')
def vegetable_baskets():
    # 获取当前页码，默认为第一页
    page = request.args.get('page', 1, type=int)
    start = (page - 1) * PER_PAGE
    posts_vegetable_baskets = fetch_data('SELECT * FROM `market_prices` WHERE query_time = DATE(now()) LIMIT %s, %s',(start, PER_PAGE))
    total_posts = fetch_data('SELECT COUNT(*) AS count FROM `market_prices` WHERE query_time = DATE(now())')[0]['count']
    total_pages = total_posts // PER_PAGE + (1 if total_posts % PER_PAGE > 0 else 0)
    return render_template('vegetable_baskets.html', posts=posts_vegetable_baskets, total_pages=total_pages,current_page=page)

@app.route('/weather')
def weather():
    weather_now = fetch_data("""
            SELECT * 
            FROM `weather` 
            ORDER BY `datetime` DESC 
            LIMIT 1;
    """)
    return render_template('weather.html', posts=weather_now)

server = pywsgi.WSGIServer(('0.0.0.0', 5001), app)
server.serve_forever()